package com.zs4sdk;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.zs4sdk.activity.Zs4GameBindSafeAccountActivity;
import com.zs4sdk.activity.Zs4GameBindSafePhoneActivity;
import com.zs4sdk.activity.Zs4GameShowWebViewActivity;
import com.zs4sdk.activity.Zs4GameVoucherActivity;
import com.zs4sdk.activity.Zs4GameAccountCenterActivity;
import com.zs4sdk.activity.Zs4GameGridMenuActivity;
import com.zs4sdk.activity.login.Zs4GameLoginActivity;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.EventHandler2Get;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.extra.Zs4GameCode;
import com.zs4sdk.service.SDKGameMenuService;
import com.common.library.util.ActivityHelper;
import com.common.library.util.Helper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;


/**
 * function: 提供菜单方法，但不公开(菜单和SDK进页面都调用这个类)
 *
 * @ author: aXiBa
 */
public class Zs4GameMenu {

    public static final String TAG = Zs4GameMenu.class.getSimpleName();


    /**
     * function: 启动菜单
     *
     * @param ctx
     * @ author: aXiBa 2013-11-19 下午3:11:44
     */
    public static void startMenu(Context ctx) {

        Zs4GameData.getInstance().setShowLogoButon(true);
        ctx.sendBroadcast(new Intent((Zs4GameBase.getPackageName() + SDKGameMenuService.ACTION_START_MENU_POSTFIX)));
    }


    /**
     * function: 显示开始菜单
     *
     * @param ctx
     * @ author: aXiBa 2013-3-26 上午11:30:46
     */
    private static void showStartMenu(Context ctx) {

        if (Zs4GameData.getInstance().isShowLogoButon()) {

            SDKGameMenuService.setPauseMenuForSdk(false);

            ctx.sendBroadcast(new Intent((Zs4GameBase.getPackageName() + SDKGameMenuService.ACTION_MENU_SHOW_START_POSTFIX)));
        }
    }


    /**
     * function: 根据flag关闭页面，显示开始菜单
     *
     * @ author: aXiBa 2013-4-2 上午11:05:48
     */
    public static void closeActivitysAndShowStartMenu(Context ctx, String flag) {

        closeActivitys(ctx, flag);

        showStartMenu(ctx);
    }

    public static void closeActivitysAndShowStartMenu1(Context ctx, String flag) {

        closeActivitys(ctx, flag);

       // showStartMenu(ctx);
    }
    /**
     * function: 根据flag关闭页面
     *
     * @ author: aXiBa 2013-4-2 上午11:05:48
     */
    private static void closeActivitys(Context ctx, String flag) {

        // 关闭flag的所有页面
        Intent intent = new Intent((Zs4GameBase.getPackageName() + Extra.ACTIONKEY.CLOSEACTIVITY_POSTFIX_MENU));
        intent.putExtra(Extra.INTENTKEY.CLOSEFLAG, flag);
        ctx.sendBroadcast(intent);
    }


    /**
     * function: 通知菜单屏幕方向改变
     *
     * @ author: aXiBa 2013-3-22 上午11:21:06
     */
    public static void notifyMenuScreenOrientationChange(Context ctx) {

        Intent intent = new Intent(Zs4GameBase.getPackageName() + SDKGameMenuService.ACTION_SCREENORIENTATION_CHANGE_POSTFIX);
        ctx.sendBroadcast(intent);
    }


    /**
     * function: 隐藏开始菜单
     *
     * @param ctx
     * @ author: aXiBa 2013-12-23 下午4:13:21
     */
    public static void hiddenStartMenu(Context ctx) {

        Intent intent = new Intent(Zs4GameBase.getPackageName() + SDKGameMenuService.ACTION_MENU_HIDE_START_POSTFIX);
        ctx.sendBroadcast(intent);
    }


    /**
     * function:
     *
     * @param ctx
     * @param cls
     * @param flag
     * @param params
     * @ author: aXiBa 2013-4-1 下午3:07:32
     */
    public static void startActivity(Context ctx, Class cls, String flag, HashMap<String, String> params) {

        Intent intent = new Intent(ctx, cls);
        intent.putExtra(Extra.INTENTKEY.SCREEN_ORIENTATION, Zs4GameBase.getScreen_orientation());
        intent.putExtra(Extra.INTENTKEY.FLAG, flag);
        if (Helper.isNotEmpty(params)) {
            Iterator<Entry<String, String>> mIte = params.entrySet().iterator();
            while (mIte.hasNext()) {
                Entry<String, String> entry = mIte.next();
                intent.putExtra(entry.getKey(), entry.getValue());
            }
        }
//		if(Extra.FLAG_MENU.equals(flag)||Extra.FLAG_MENU_ACCOUNT.equals(flag)) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		}
        ctx.startActivity(intent);
    }


    /**
     * function: 进入充值中心/有传goodsid为支付中心
     * @param ctx
     * @param flag
     * @param packageName
     * @ author: aXiBa 2013-4-15 上午10:27:49
     */
    public static void enterVoucherCenter(Context ctx, String flag, String packageName, String good_code, String cp_order_id,int price,int count) {


//        if (!(Zs4GameData.getInstance().isVerify())) {
//            new VerifyIdCardDialog(ctx, true).show();
//            return;
//        }


        hiddenStartMenu(ctx);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Zs4GameBase.KEY_PAY_URL, Extra.URL.VOUCHER_API);
        params.put(Zs4GameBase.KEY_GOODS_ID, good_code);
        params.put(Zs4GameBase.KEY_CP_ORDER_ID, cp_order_id);
        params.put(Extra.INTENTKEY.INTENT_TYPE, Extra.INTENTKEY.GAME_TPYE);

        params.put(Extra.INTENTKEY.GOOD_PRICE,price+"");
        params.put(Extra.INTENTKEY.GOOD_COUNT,count+"");

        params.put(Extra.INTENTKEY.BACKSENDMESSAGE, Extra.BOOLEAN_TRUE);

        startActivity(ctx, Zs4GameVoucherActivity.class, flag, params);
    }


    /**
     * function: 进入账号中心
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @ author: aXiBa 2013-4-15 上午10:24:11
     */
    public static void enterAccountCenter(Context ctx, String flag, String packageName) {

        hiddenStartMenu(ctx);

        if (Zs4GameData.getInstance().isLogined()) {
//			if (Zs4GameData.getInstance().isGuest()){
//				startActivity(ctx, zs4gameGameUpdateGuestActivity.class, flag, null);
//			}else {
          //  startActivity(ctx, Zs4GameAcountCenterActivity.class, flag, null);
            startActivity(ctx, Zs4GameAccountCenterActivity.class, flag, null);
//			}
        } else {
            startActivity(ctx, Zs4GameLoginActivity.class, flag, null);
        }
    }

    /**
     * function: 进入账号中心
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @ author: aXiBa 2013-4-15 上午10:24:11
     */
    public static void enterBindAccount(Context ctx, String flag, String packageName) {

        hiddenStartMenu(ctx);

        if (Zs4GameData.getInstance().isLogined()) {
//			if (Zs4GameData.getInstance().isGuest()){
//				startActivity(ctx, zs4gameGameUpdateGuestActivity.class, flag, null);
//			}else {
            if(Extra.isComplex()){//繁体
                startActivity(ctx, Zs4GameBindSafeAccountActivity.class, flag, null);
            }else{//简体
                startActivity(ctx, Zs4GameBindSafePhoneActivity.class, flag, null);
            }

//			}
        } else {
            startActivity(ctx, Zs4GameLoginActivity.class, flag, null);
        }
    }

    /**
     * function: 注销处理
     * <p>
     * 1.6注销后显示的登录页面，没有再显示悬浮菜单
     * 1.7注销后显示的悬浮菜单
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @ author: aXiBa 2013-4-15 上午10:30:28
     */
    public static void logoutHandle(Context ctx, String flag, String packageName, String msg) {

        if (!Zs4GameData.getInstance().isLogined()) {
            Helper.showToast(ctx, Helper.getStringResId(ctx, packageName, "zs4gamestring_hint_please_login"));

            closeActivitysAndShowStartMenu1(ctx, flag);

            // 注销失败，还未登录消息
            if (Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
                ActivityHelper.sendBroadcast(Zs4GameBase.getPackageName().concat(Extra.ACTIONKEY.MESSAGE_POSTFIX), Zs4GameCode.LOGOUTFAIL_NOTLOGIN, ctx);
            } else {
                ActivityHelper.sendBroadcast(flag, Zs4GameCode.LOGOUTFAIL_NOTLOGIN, ctx);
            }
        } else {
            doLogout(ctx, flag, packageName, msg);
        }
    }


    /**
     * function: 程序调用注销
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @ author: aXiBa 2013-12-13 下午6:47:14
     */
    public static void logoutByProgram(Context ctx, String flag, String packageName, String msg) {

        // 注册广播接收
        doLogout(ctx, flag, packageName, msg);
    }


    /**
     * function: 未登陆直接返回登陆
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @ author: aXiBa 2013-12-13 下午6:47:14
     */
    public static void reLoginWithoutBefore(Context ctx, String flag, String packageName, String msg) {

        reLogin(ctx, flag, packageName, msg);
    }


    /**
     * function: 注销操作
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @param logout_msg
     * @ author: aXiBa 2013-12-13 下午6:46:27
     */
    private static void doLogout(Context ctx, String flag, String packageName, String logout_msg) {


        // 有网络的时候才发信息给服务器
        if (NetworkHelper.isNetworkAvailable(ctx)) {

            new EventHandler2Get(
                    Extra.URL.LOGOUTURL,
                    ParamsHelper.getLogOutParam("1"),
                    ParamsHelper.getUserAgent1(),
                    new ResultHandlerInEvent() {

                        @Override
                        public void doResultHanler(JSONObject result) throws JSONException {
                            LogUtil.i(TAG, "注销结果：" + result);

                        }

                        @Override
                        public void doExceptionHandler() {

                        }
                    });
        }


        Zs4GameTD.UpLoadLogoutInfo(ctx);

        Zs4GameData.getInstance().clearLoginInfo();
      //  Zs4GameData.getInstance().clearLastLoginUserInfo();
        if (Helper.isNotNull(logout_msg)) {
            Helper.showToast(ctx, logout_msg);
        }

        closeActivitysAndShowStartMenu1(ctx, flag);

        // 注销消息
        if (Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
//			LogUtil.i(TAG, "注销结果：1111111111111111111111111111111");
            ActivityHelper.sendBroadcast(Zs4GameBase.getPackageName().concat(Extra.ACTIONKEY.LOGOUT_POSTFIX), Zs4GameCode.LOGOUTSUCCESS, ctx);
        } else {
//			LogUtil.i(TAG, "注销结果：222222222222222222222222");
            ActivityHelper.sendBroadcast(flag, Zs4GameCode.LOGOUTSUCCESS, ctx);
        }
//		goLoginOrRegister(ctx);

        Zs4GameMenu.hiddenStartMenu(ctx);
    }

    /**
     * function: 到登录或者注册页面
     *
     * @param ctx
     * @ author: aXiBa 2013-12-12 下午12:01:16
     */
    private static void goLoginOrRegister(Context ctx) {


        // 隐藏悬浮菜单
        Zs4GameMenu.hiddenStartMenu(ctx);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Extra.INTENTKEY.BACKSENDMESSAGE, Extra.BOOLEAN_TRUE);
        Zs4GameMenu.startActivity(ctx, Zs4GameLoginActivity.class, Zs4GameBase.getPackageName().concat(Extra.ACTIONKEY.LOGIN_POSTFIX), params);

    }


    /**
     * * function: 未登陆，直接返回登陆操作
     *
     * @param ctx
     * @param flag
     * @param packageName
     * @param logout_msg
     * @ author:Jancy_Weng 20150821
     */
    private static void reLogin(Context ctx, String flag, String packageName, String logout_msg) {

        Helper.showToast(ctx, logout_msg);

        closeActivitysAndShowStartMenu(ctx, flag);

        ActivityHelper.sendBroadcast(flag, Zs4GameCode.LOGOUTSUCCESS, ctx);
    }


    /**
     * function: 显示webview
     *
     * @param ctx
     * @param title
     * @param url
     * @param flag
     * @param menuid
     * @ author: aXiBa 2013-3-26 上午11:14:09
     */
    public static void showWebView(Context ctx, String title, String url, String flag, String menuid) {

        // 在线客服也需要登录
//		if(Extra.MENUID.SERVICEONLINE.equals(menuid) && !Zs4GameData.getInstance().isLogined()) {
//			hiddenStartMenu(ctx);
//			startActivity(ctx, Zs4GameLoginActivity.class, flag, null);
//		}
//		else {
        hiddenStartMenu(ctx);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Extra.INTENTKEY.TITLE, title);
        params.put(Extra.INTENTKEY.URL, url);
        startActivity(ctx, Zs4GameShowWebViewActivity.class, flag, params);
//		}
    }


    /**
     * function: webview显示协议
     *
     * @param ctx
     * @ author: aXiBa 2013-3-26 上午11:14:09
     */
    public static void showWebViewForProtocol(Context ctx) {

        String CompanyPro = null;
        CompanyPro = ctx.getString(ActivityHelper.getStringResId("zs4gamestring_text_protocol_title"));


        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Extra.INTENTKEY.TITLE, CompanyPro);
        params.put(Extra.INTENTKEY.URL, Extra.URL.PROTOCOLURL);
        params.put(Extra.INTENTKEY.ISSHOW_SDKVERSION, Extra.BOOLEAN_TRUE);
        startActivity(ctx, Zs4GameShowWebViewActivity.class, "", params);
    }


    /**
     * function: 启动服务
     *
     * @param ctx
     * @ author: aXiBa 2013-11-19 下午3:15:16
     */
    public static void startService(Context ctx, String packageName) {
        Log.e(TAG, "startService............");

        Intent intent = new Intent();
        intent.setClass(ctx, SDKGameMenuService.class);
        intent.putExtra(Extra.INTENTKEY.PACKAGENAME, packageName);
        ctx.startService(intent);
    }


    /**
     * function: stop服务
     *
     * @ author: aXiBa 2013-3-7 上午10:48:02
     */
    public static void stopService(Context ctx) {
        Log.e(TAG, "stopService............");

        Intent intent = new Intent();
        intent.setClass(ctx, SDKGameMenuService.class);
        ctx.stopService(intent);

    }


    /**
     * function: 显示宫格菜单
     *
     * @param ctx
     * @param flag
     * @ author: aXiBa 2013-12-9 下午6:17:49
     */
    public static void showGridMenu(Context ctx, String flag) {

        hiddenStartMenu(ctx);

        if (Zs4GameData.getInstance().isLogined()) {
            startActivity(ctx, Zs4GameGridMenuActivity.class, flag, null);
        } else {
            startActivity(ctx, Zs4GameLoginActivity.class, flag, null);
        }
    }


    /**
     * function: 输入登录：同步本地自动分配信息
     *
     * @param entity
     * @ author: aXiBa 2013-12-18 下午3:42:37
     */
    public static void synLocalAutoAssignInfo(LoginJSONResultEntity entity, String account, String password) {

        // 获取本地用户信息
        LoginJSONResultEntity entity_local = Zs4GameData.getInstance().getLocalUserInfo(entity.getUserId());
        if (Helper.isNotNull(entity_local)) {
            String email_local = entity_local.getUsercode();
            String password_local = entity_local.getPassword();
            if (!account.equalsIgnoreCase(email_local)) {   // 邮箱不区分大小写
                entity.setFlag_updateEmail(Extra.BOOLEAN_TRUE);
            } else {
                entity.setFlag_updateEmail(entity_local.getFlag_updateEmail());
            }

            if (Helper.isNotEmpty(password_local) && !password.equals(password_local)) {
                entity.setFlag_updatePassword(Extra.BOOLEAN_TRUE);
                entity.setPassword("");
            } else {
                entity.setFlag_updatePassword(entity_local.getFlag_updatePassword());
                entity.setPassword(entity_local.getPassword());
            }

            if (!account.equalsIgnoreCase(email_local) ||
                    (Helper.isNotEmpty(password_local) && !password.equals(password_local))) {
                entity.setIsAutoAssign(Extra.BOOLEAN_FALSE);
            } else {
                entity.setIsAutoAssign(entity_local.getIsAutoAssign());
            }
        }
    }


    /**
     * function: 切换账号:同步本地自动分配信息
     *
     * @param entity
     * @ author: aXiBa 2013-12-18 下午6:41:36
     */
    public static void synLocalAutoAssignInfo(LoginJSONResultEntity entity) {

        // 获取本地用户信息
        LoginJSONResultEntity entity_local = Zs4GameData.getInstance().getLocalUserInfo(entity.getUserId());
        if (Helper.isNotNull(entity_local)) {
//			entit
            entity.setIsAutoAssign(entity_local.getIsAutoAssign());
            entity.setFlag_updateEmail(entity_local.getFlag_updateEmail());
            entity.setFlag_updatePassword(entity_local.getFlag_updatePassword());
            entity.setPassword(entity_local.getPassword());
        }
    }
}
